"""Moves activity column and its value from the participant model to the participant role model

Revision ID: 4b65941d065a
Revises: 3b0f5b81376f
Create Date: 2022-10-26 16:02:26.996119

"""
from alembic import op
import sqlalchemy as sa

from pydantic.types import constr, conint

from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session


PrimaryKey = conint(gt=0, lt=2147483647)
NameStr = constr(regex=r"^(?!\s*$).+", strip_whitespace=True, min_length=3)

Base = declarative_base()

# revision identifiers, used by Alembic.
revision = "4b65941d065a"
down_revision = "3b0f5b81376f"
branch_labels = None
depends_on = None


class Participant(Base):
    __tablename__ = "participant"
    id = Column(Integer, primary_key=True)
    activity = Column(Integer)
    participant_roles = relationship(
        "ParticipantRole", backref="participant", lazy="subquery", cascade="all, delete-orphan"
    )


class ParticipantRole(Base):
    __tablename__ = "participant_role"
    id = Column(Integer, primary_key=True)
    activity = Column(Integer)
    participant_id = Column(Integer, ForeignKey("participant.id", ondelete="CASCADE"))


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("participant_role", sa.Column("activity", sa.Integer(), nullable=True))

    bind = op.get_bind()
    session = Session(bind=bind)

    print("Migrating participant activity to participant role activity...")

    participants = session.query(Participant).all()
    for participant in participants:
        participant_activity = participant.activity
        for participant_role in participant.participant_roles:
            participant_role.activity = participant_activity
            session.add(participant_role)
            session.commit()

    print("Participant activity to participant role activity migrated.")

    op.drop_column("participant", "activity")
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("participant_role", "activity")
    op.add_column(
        "participant", sa.Column("activity", sa.INTEGER(), autoincrement=False, nullable=True)
    )
    # ### end Alembic commands ###
